<template lang="">
    <div class="coat">
      <div class="theSlot">
        <slot></slot>
      </div>
      <div class="imgFrame">
        <input v-if=theNeededOne type="file" accept="image/*" ref="reference" @change="handleFileUpload" required/>
        <input v-if=theNeedlessOne type="file" accept="image/*" ref="reference" @change="handleFileUpload" />
        <img class="imgUploaded" :src="src" alt="!" @click="triggerInput">
      </div>
    </div>
</template>
<script>
export default {
  name: "handleFileUpload",
  props: {
    keyName: String,
    needed: String
  },
  data() {
    return {
      msg: {
        img: File,
        key: '',
      },
      src: '',
    }
  },
  computed: {    /* 根据prop判断是否required */
    theNeededOne() {
      switch (this.needed) {
        case 'true':
          return true;
        default:
          return false;
      }
    },
    theNeedlessOne() {
      switch (this.needed) {
        case 'false':
          return true;
        default:
          return false;
      }
    }
  },
  methods: {
    handleFileUpload(eve) {
      const file = eve.target.files[0];

      const formData = new FormData(); // 创建一个FormData对象
      const keyName = this.keyName;
      formData.append(keyName, file); // 将选中的文件添加到FormData对象中，'image'为图片文件的键名

      //传给父组件
      this.msg.img = file;
      this.msg.key = keyName;
      this.$emit('childMessage', this.msg);

      // 显示
      const that = this;
      if (!eve || !window.FileReader) return; // 看是否支持FileReader
      const reader = new FileReader();
      reader.readAsDataURL(file); // 转换为url
      reader.onloadend = function () {
        that.src = this.result;//将转换完成的url赋给src
      }
    },
    triggerInput() {
      this.$refs.reference.click();   //实现修改图片
    }
  }
}
</script>
<style scoped>
/* 图片未上传时，不让img标签显示图裂图标和alt */
img[src=""],
img:not([src]) {
  opacity: 0;
}

img {
  overflow: hidden;
  width: 100px;

  z-index: 2;
}

input[type='file'] {
  opacity: 0;
  width: 100px;
  height: 100px;
  z-index: 99;

  border-radius: 8px;
}

.coat {
  position: relative;
  width: 100px;
  height: 100px;

  margin-right: 12px;
  margin-bottom: 12px;

  float: left;

  display: flex;
  flex-direction: column;
  align-items: center;
}

.imgFrame {
  position: relative;

  height: 100px;
  width: 100px;
  overflow: hidden;
  object-fit: contain;
  background-repeat: no-repeat;
  background-image: url('../assets/images/photo-frame.png');
  border-radius: 8px;
}

.imgUploaded {
  object-fit: contain;
  position: absolute;
  top: 0;
  left: 0;
}

.theSlot {
  position: absolute;
  top: 60px;
  z-index: 1;
}
</style>